# -*- coding: utf-8 -*-
import sys

sys.setrecursionlimit(100000)  # 例如这里设置为十万
from datetime import datetime, date, timedelta
import time
import string
import random
from django.db import models
from django.db.models import Sum
import django.utils.timezone as timezone
from DjangoUeditor.models import UEditorField
from apps.map import *


# Create your models here.


def random_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for x in range(size))


class Purchase(models.Model):

    def __init__(self, *args, **kwargs):
        super(Purchase, self).__init__(*args, **kwargs)  # 在先
        x = self.purchase_goodinpurchase.all()
        if x.exists():
            self.amount = x.aggregate(Sum('amount'))['amount__sum'] - self.discount

    code = models.CharField(verbose_name='订单号', max_length=100, blank=True, null=True, unique=True)
    fk_store = models.ForeignKey(
        verbose_name='货源',
        blank=True,
        null=True,
        to='organization.Store',
        related_name='store_purchase',
        # on_delete=models.CASCADE
    )
    fk_clerk = models.ForeignKey(
        verbose_name='店员',
        blank=True,
        null=True,
        to='user.Clerk',
        related_name='clerk_purchase'
        # on_delete=models.CASCADE
    )
    discount = models.IntegerField(verbose_name="满减", blank=True, null=True, default=0)
    amount = models.IntegerField(verbose_name="金额", blank=True, null=True, default=0)
    info = models.TextField(verbose_name='备注', blank=True, null=True)
    created = models.DateTimeField(verbose_name='创建时间', blank=True, null=True, default=timezone.now)
    modified = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=timezone.now)

    # 进货金额每单
    def amount_each_purchase(self):
        goodsinpurchase = self.purchase_goodinpurchase.all()  # queryset
        r = 0
        if goodsinpurchase.exists():
            for good in goodsinpurchase:
                r += good.amount()
        return r

    # 进货金额每天
    def amount_each_day(self):
        created = self.created  # datetime  ****/**/** **:**:**
        today = created.date()  # date ****/**/**
        yesterday = today + timedelta(days=-1)  # date
        tomorrow = today + timedelta(days=1)  # date

        today = today.timetuple()  # date -> timetuple  ****/**/** 00:00:00  一天的开始
        today = time.mktime(today)  # timetuple -> timestamp
        today = datetime.fromtimestamp(today)  # timestamp -> datetime  ****/**/** 00:00:00  一天的开始
        tomorrow = datetime.fromtimestamp(time.mktime(tomorrow.timetuple()))

        r = 0
        for purchase in Purchase.objects.filter(created__gte=today, created__lt=tomorrow):
            r += purchase.amount_each_purchase()
        return r

    class Meta:
        verbose_name = "进货单据"
        verbose_name_plural = verbose_name
        ordering = ["fk_store"]
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    def save(self, *args, **kwargs):
        self.modified = timezone.now()
        if not self.code:
            now = datetime.now()  # datetime 时间元组
            str_datetime = now.strftime("%Y%m%d%H%M%S")
            str_microsecond = str(now.timestamp()).split('.')[1].rjust(6, '0')
            #  now.timestamp()  # 保留六位小数0.123456，精确到microsecond微秒 注意不足六位的情况0.100000 float 0.1
            # rjust 右对齐后 填充左边
            str_random = random_generator(6)
            self.code = "{}{}{}".format(str_datetime, str_microsecond, str_random)  # 8+6+6
        super(Purchase, self).save(*args, **kwargs)  # Call the "real" save() method.

    def __str__(self):
        return self.code or 'None Code'


class GoodInPurchase(models.Model):
    fk_purchase = models.ForeignKey(
        verbose_name='进货单据',
        blank=False,
        to='Purchase',
        related_name='purchase_goodinpurchase',
        # on_delete=models.CASCADE
    )
    fk_good = models.ForeignKey(
        verbose_name='商品',
        blank=False,
        to='good.Good',
        related_name='good_goodinpurchase',
        # on_delete=models.CASCADE
    )
    quantity = models.IntegerField(verbose_name="数量")
    discount = models.IntegerField(verbose_name="优惠", blank=True, null=True, default=0)
    amount = models.IntegerField(verbose_name='金额', blank=True, null=True, default=0)
    delivered = models.CharField(verbose_name="配送", blank=True, null=True, max_length=10, choices=DELIVER)
    info = models.TextField(verbose_name='备注', blank=True, null=True)
    created = models.DateTimeField(verbose_name='创建时间', blank=True, null=True, default=timezone.now)
    modified = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=timezone.now)

    class Meta:
        verbose_name = "进货单据商品清单"
        verbose_name_plural = verbose_name
        ordering = ["fk_purchase"]
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    def save(self, *args, **kwargs):
        self.modified = timezone.now()
        self.amount = self.quantity * (self.fk_good.price_purchase - self.discount)
        super(GoodInPurchase, self).save(*args, **kwargs)  # Call the "real" save() method.


class Sale(models.Model):
    '''
    交易
    '''

    def __init__(self, *args, **kwargs):
        super(Sale, self).__init__(*args, **kwargs)  # 在先
        x = self.sale_goodinsale.all()
        if x.exists():
            self.amount = x.aggregate(Sum('amount'))['amount__sum'] - self.discount
            self.interests = x.aggregate(Sum('interests'))['interests__sum'] - self.discount

    code = models.CharField(verbose_name='订单号', max_length=100, blank=True, null=True, unique=True)
    fk_store = models.ForeignKey(
        verbose_name='店铺',
        blank=True,
        null=True,
        to='organization.Store',
        related_name='store_sale',
        # on_delete=models.CASCADE
    )
    fk_clerk = models.ForeignKey(
        verbose_name='店员',
        blank=True,
        null=True,
        to='user.Clerk',
        related_name='clerk_sale',
        # on_delete=models.CASCADE
    )
    fk_customer = models.ForeignKey(
        blank=True,
        null=True,
        verbose_name='顾客',
        to='user.Customer',
        related_name='customer_sale',
        # on_delete=models.CASCADE
    )
    created = models.DateTimeField(verbose_name='创建时间', blank=True, null=True, default=timezone.now)
    modified = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=timezone.now)
    discount = models.IntegerField(verbose_name='满减', blank=True, null=True, default=0)
    amount = models.IntegerField(verbose_name="金额", blank=True, null=True, default=0)
    interests = models.IntegerField(verbose_name="毛利", blank=True, null=True, default=0)
    info = models.TextField(verbose_name='备注', blank=True, null=True)

    class Meta:
        verbose_name = "售货单据"
        verbose_name_plural = verbose_name
        ordering = ["-created"]
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    # 销售金额每单
    def amount_each_sale(self):
        goodsinsale = self.sale_goodinsale.all()  # queryset
        r = 0
        if goodsinsale.exists():
            for good in goodsinsale:
                r += good.amount()
        return r - self.discount

    # 销售金额每天
    def amount_each_day(self):
        created = self.created  # datetime  ****/**/** **:**:**
        today = created.date()  # date ****/**/**
        yesterday = today + timedelta(days=-1)  # date
        tomorrow = today + timedelta(days=1)  # date

        today = today.timetuple()  # date -> timetuple  ****/**/** 00:00:00  一天的开始
        today = time.mktime(today)  # timetuple -> timestamp
        today = datetime.fromtimestamp(today)  # timestamp -> datetime  ****/**/** 00:00:00  一天的开始
        tomorrow = datetime.fromtimestamp(time.mktime(tomorrow.timetuple()))

        r = 0
        for purchase in Purchase.objects.filter(created__gte=today, created__lt=tomorrow):
            r += purchase.amount_each_purchase()
        return r

    def amount_each_month(self):
        pass

    def amount_each_year(self):
        pass

    def sale_date(self):
        return self.created.date()

    def sale_time(self):
        return self.created.time()

    def save(self, *args, **kwargs):
        self.modified = timezone.now()
        if not self.code:
            now = datetime.now()  # datetime 时间元组
            str_datetime = now.strftime("%Y%m%d%H%M%S")
            str_microsecond = str(now.timestamp()).split('.')[1].rjust(6, '0')
            #  now.timestamp()  # 保留六位小数0.123456，精确到microsecond微秒 注意不足六位的情况0.100000 float 0.1
            # rjust 右对齐后 填充左边
            str_random = random_generator(6)
            self.code = "{}{}{}".format(str_datetime, str_microsecond, str_random)  # 8+6+6
        super(Sale, self).save(*args, **kwargs)  # Call the "real" save() method.

    def __str__(self):
        return self.code or 'None Code'


class GoodInSale(models.Model):
    '''
    售货单据商品清单
    '''

    def __init__(self, *args, **kwargs):
        super(GoodInSale, self).__init__(*args, **kwargs)  # 在先

    fk_sale = models.ForeignKey(
        verbose_name='售货单据',
        blank=False,
        to='Sale',
        related_name='sale_goodinsale',
        # on_delete=models.CASCADE
    )
    fk_good = models.ForeignKey(
        verbose_name='商品',
        blank=False,
        to='good.Good',
        # limit_choices_to={},  # https://docs.djangoproject.com/en/1.11/ref/models/fields/
        related_name='good_goodinsale',
        # on_delete=models.CASCADE
    )
    quantity = models.IntegerField(verbose_name="数量")
    discount = models.FloatField(verbose_name="折扣", blank=True, null=True, default=0)
    amount = models.IntegerField(verbose_name="金额", blank=True, null=True, default=0)
    interests = models.IntegerField(verbose_name="毛利", blank=True, null=True, default=0)
    delivered = models.CharField(verbose_name="配送", blank=True, null=True, max_length=10, choices=DELIVER)
    info = models.TextField(verbose_name='备注', blank=True, null=True)
    created = models.DateTimeField(verbose_name='创建时间', blank=True, null=True, default=timezone.now)
    modified = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=timezone.now)

    class Meta:
        verbose_name = "售货单据商品清单"
        verbose_name_plural = verbose_name
        ordering = ["fk_sale"]
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    def save(self, *args, **kwargs):
        self.modified = timezone.now()
        self.amount = self.quantity * (self.fk_good.price_sell - self.discount)
        self.interests = self.amount - self.quantity * self.fk_good.price_purchase
        super(GoodInSale, self).save(*args, **kwargs)  # Call the "real" save() method.

    def save_models(self):
        # 字段联动
        pass


class SaleComment(models.Model):
    fk_sale = models.ForeignKey(
        verbose_name='售货单据',
        blank=False,
        to='Sale',
        # on_delete=models.CASCADE
    )
    comment_service = models.CharField(verbose_name='导购服务', blank=True, null=True, max_length=2, choices=COMMENT_RANK)
    comment_environment = models.CharField(verbose_name='店铺环境', blank=True, null=True, max_length=2,
                                           choices=COMMENT_RANK)
    comment_logistics = models.CharField(verbose_name='交易物流', blank=True, null=True, max_length=2, choices=COMMENT_RANK)
    created = models.DateTimeField(verbose_name='创建时间', blank=True, null=True, default=timezone.now)
    modified = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=timezone.now)

    class Meta:
        verbose_name = "交易评价"
        verbose_name_plural = verbose_name
        ordering = ["fk_sale"]
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    def save(self, *args, **kwargs):
        self.modified = timezone.now()
        super(SaleComment, self).save(*args, **kwargs)  # Call the "real" save() method.


class GoodComment(models.Model):
    fk_good = models.ForeignKey(
        verbose_name='商品',
        blank=False,
        to='GoodInSale',
        # on_delete=models.CASCADE
    )
    comment_describe = models.CharField(verbose_name='描述相符', blank=True, null=True, max_length=2, choices=COMMENT_RANK)
    created = models.DateTimeField(verbose_name='创建时间', blank=True, null=True, default=timezone.now)
    modified = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=timezone.now)

    info = UEditorField(
        verbose_name=u'商品评价',
        blank=True,
        null=True,
        width=600, height=300,
        # toolbars="full",
        imagePath="invoice/good_comment/",  # 相对路径
        filePath="invoice/good_comment/",
        default=""  # 新增字段时，为避免出错可以设置default=""
        # upload_settings={"imageMaxSize":1204000},
        # settings={},
        # command=None,
        # event_handler=myEventHander(),
        # blank=True
    )

    class Meta:
        verbose_name = "商品评价"
        verbose_name_plural = verbose_name
        ordering = ["fk_good"]
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    def save(self, *args, **kwargs):
        self.modified = timezone.now()
        super(GoodComment, self).save(*args, **kwargs)  # Call the "real" save() method.


class Refund(models.Model):
    code = models.CharField(verbose_name='订单号', max_length=100, blank=True, null=True, unique=True)
    fk_goodinpurchase = models.ForeignKey(
        verbose_name='已购商品',
        blank=False,
        to='invoice.GoodInPurchase',
        # on_delete=models.CASCADE
    )
    quantity = models.IntegerField(verbose_name="数量")
    info = models.TextField(verbose_name='备注', blank=True, null=True)
    created = models.DateTimeField(verbose_name='创建时间', blank=True, null=True, default=timezone.now)
    modified = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=timezone.now)

    class Meta:
        verbose_name = "退货单据"
        verbose_name_plural = verbose_name
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    def save(self, *args, **kwargs):
        self.modified = timezone.now()
        if not self.code:
            now = datetime.now()  # datetime 时间元组
            str_datetime = now.strftime("%Y%m%d%H%M%S")
            str_microsecond = str(now.timestamp()).split('.')[1].rjust(6, '0')
            #  now.timestamp()  # 保留六位小数0.123456，精确到microsecond微秒 注意不足六位的情况0.100000 float 0.1
            # rjust 右对齐后 填充左边
            str_random = random_generator(6)
            self.code = "{}{}{}".format(str_datetime, str_microsecond, str_random)  # 8+6+6
        super(Refund, self).save(*args, **kwargs)  # Call the "real" save() method.


class Expense(models.Model):
    code = models.CharField(verbose_name='订单号', max_length=100, blank=True, null=True, unique=True)
    amount = models.IntegerField(verbose_name="金额", blank=True, null=True, default=0)
    type = models.CharField(verbose_name="类型", max_length=10, choices=EXPENSE_TYPE, blank=True, null=True)
    info = models.TextField(verbose_name='备注', blank=True, null=True)
    created = models.DateTimeField(verbose_name='创建时间', blank=True, null=True, default=timezone.now)
    modified = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=timezone.now)
    fk_store = models.ForeignKey(
        verbose_name='店铺',
        blank=True,
        null=True,
        to='organization.Store',
        limit_choices_to={'is_own': '00'},
        # on_delete=models.CASCADE
    )

    class Meta:
        verbose_name = "费用"
        verbose_name_plural = verbose_name
        # db_table  # default app_model
        # unique_together = (("field", "field"),)

    def save(self, *args, **kwargs):
        self.modified = timezone.now()
        if not self.code:
            now = datetime.now()  # datetime 时间元组
            str_datetime = now.strftime("%Y%m%d%H%M%S")
            str_microsecond = str(now.timestamp()).split('.')[1].rjust(6, '0')
            #  now.timestamp()  # 保留六位小数0.123456，精确到microsecond微秒 注意不足六位的情况0.100000 float 0.1
            # rjust 右对齐后 填充左边
            str_random = random_generator(6)
            self.code = "{}{}{}".format(str_datetime, str_microsecond, str_random)  # 8+6+6
        super(Expense, self).save(*args, **kwargs)  # Call the "real" save() method.

